from contextlib import contextmanager

@contextmanager
def task_lifecycle(task_name):
    print(f"Task '{task_name}' started")
    try:
        yield  # 执行任务
    except Exception as e:
        print(f"Task '{task_name}' failed with error: {e}")
    finally:
        print(f"Task '{task_name}' completed")

# 模拟任务
def perform_task(task_name, should_fail=False):
    with task_lifecycle(task_name):
        print(f"Performing task '{task_name}'...")
        if should_fail:
            raise ValueError("Something went wrong!")
        print(f"Task '{task_name}' succeeded")

# 运行任务
perform_task("Task A")  # 正常任务
perform_task("Task B", should_fail=True)  # 失败任务